<template>
  <div style="padding-bottom: 16px">
    <a-space>
      <a-button type="primary" @click="handleOpenCreateModal"
        >新建计划（发给好友）</a-button
      >
      <a-button type="primary" @click="handleOpenCreateGroupModal"
        >新建计划（发到群）</a-button
      >
      <a-button type="primary" status="warning" @click="handleDeleteSentTasks"
        >删除已发任务</a-button
      >
      <a-button type="primary" status="warning" @click="handleResetFailedTasks"
        >重置失败任务</a-button
      >
      <a-button type="primary" status="warning" @click="handleClearAllTasks"
        >清空任务表</a-button
      >
      <!-- <a-button type="primary">获取群发计划</a-button> -->
    </a-space>
  </div>
  <div>
    <a-table
      row-key="_id"
      :data="taskList"
      :columns="columns"
      :loading="loading"
      :pagination="{
        total: count,
        current: current,
        pageSize: pageSize,
        showTotal: true,
        showPageSize: true,
      }"
      :row-selection="{
        type: 'checkbox',
        showCheckedAll: true,
        onlyCurrent: false,
      }"
      v-model:selectedKeys="selectedKeys"
      @page-change="handlePageChange"
      @page-size-change="handlePageSizeChange"
    >
      <template #nick="{ record }">
        <div>{{ record.nick }}</div>
        <div>{{ record.wxid }}</div>
      </template>
      <template #content="{ record }">
        <div>{{ record.content }}</div>
        <div>{{ record.path }}</div>
        <div>{{ record.jumpUrl }}</div>
        <div>{{ record.appid }}</div>
        <div>{{ record.gh }}</div>
      </template>
      <template #triggerTime="{ record }">
        <div v-if="!record.istask">未分配</div>
        <div v-else>
          <a-button-group>
            <a-button>{{ record.triggerTime }}</a-button>
            <a-tooltip content="重置">
              <a-button @click="handleResetTask(record)">
                <template #icon>
                  <icon-sync />
                </template>
              </a-button>
            </a-tooltip>
          </a-button-group>
        </div>
      </template>
      <template #status="{ record }">
        <div v-if="record.status === 0">未发送</div>
        <div v-else-if="record.status === 1">已发送</div>
        <div v-else-if="record.status === 2">发送失败</div>
      </template>
    </a-table>
  </div>
  <a-modal
    title="新建群发计划（好友）"
    :width="1000"
    :footer="false"
    :maskClosable="false"
    v-model:visible="visibleCreateModal"
    draggable
    @cancel="handleCreateModalCancel"
  >
    <CreateModal
      :selectedWxid="props.selectedWxid"
      @closeModal="handleCreateModalCancel"
    />
  </a-modal>

  <a-modal
    title="新建群发计划（群）"
    :width="1000"
    :footer="false"
    :maskClosable="false"
    v-model:visible="visibleCreateGroupModal"
    draggable
    @cancel="handleCreateGroupModalCancel"
  >
    <CreateGroupModal
      :selectedWxid="props.selectedWxid"
      @closeModal="handleCreateGroupModalCancel"
    />
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { Message, TableColumnData } from '@arco-design/web-vue';
  import {
    getSendTask,
    resetSendask,
    clearAllTask,
    resetFailedTasks,
    deleteSentTasks,
  } from '@/api/task';
  import CreateModal from './send-all-create-modal.vue';
  import CreateGroupModal from './send-all-create-group-modal.vue';

  const props = defineProps<{
    selectedWxid: string;
  }>();

  const taskList = ref([]);
  const selectedKeys = ref<string[]>([]);
  const current = ref(1);
  const pageSize = ref(10);
  const count = ref(0);
  const loading = ref(false);
  const searchForm = reactive({
    nick: '',
    tags: '',
    status: undefined,
    isreceive: undefined,
  });
  const columns: TableColumnData[] = [
    {
      title: '类型',
      dataIndex: 'msgtype',
    },
    {
      title: '发送内容',
      slotName: 'content',
    },
    {
      title: '接收方',
      slotName: 'nick',
    },
    {
      title: '触发时间',
      slotName: 'triggerTime',
    },
    {
      title: '状态',
      slotName: 'status',
    },
  ];

  const fetchTaskList = async (wxid: string) => {
    loading.value = true;
    try {
      const res: any = await getSendTask({
        ownerWxid: wxid,
        field: {
          nick: searchForm.nick,
          tags: searchForm.tags,
          status: searchForm.status,
          isreceive: searchForm.isreceive,
        },
        page: current.value,
        pageSize: pageSize.value,
      });
      if (res.code === 20000) {
        count.value = res.data.count;
        taskList.value = res.data.list;
      } else {
        Message.error(res.msg || '获取群发列表失败');
      }
    } catch (error) {
      console.error('获取群发列表失败:', error);
    } finally {
      loading.value = false;
    }
  };
  // 处理页码变化
  const handlePageChange = async (page: number) => {
    current.value = page;
    await fetchTaskList(props.selectedWxid);
  };
  // 处理每页条数变化
  const handlePageSizeChange = async (size: number) => {
    pageSize.value = size;
    current.value = 1; // 切换页面大小时重置为第一页
    await fetchTaskList(props.selectedWxid);
  };

  const handleResetTask = async (record: any) => {
    try {
      const res: any = await resetSendask({
        record,
      });

      if (res.code === 20000) {
        Message.success('重置成功');
        await fetchTaskList(props.selectedWxid);
      } else {
        Message.error(res.msg || '重置失败');
      }
    } catch (error) {
      Message.error('重置失败');
    }
  };

  // 删除已发任务
  const handleDeleteSentTasks = async () => {
    try {
      const res: any = await deleteSentTasks({
        ownerWxid: props.selectedWxid,
      });

      if (res.code === 20000) {
        Message.success('重置成功');
        await fetchTaskList(props.selectedWxid);
      } else {
        Message.error(res.msg || '重置失败');
      }
    } catch (error) {
      Message.error('重置失败');
    }
  };

  // 重置失败任务
  const handleResetFailedTasks = async () => {
    try {
      const res: any = await resetFailedTasks({
        ownerWxid: props.selectedWxid,
      });

      if (res.code === 20000) {
        Message.success('重置成功');
        await fetchTaskList(props.selectedWxid);
      } else {
        Message.error(res.msg || '重置失败');
      }
    } catch (error) {
      Message.error('重置失败');
    }
  };

  // 清空任务表
  const handleClearAllTasks = async () => {
    try {
      const res: any = await clearAllTask({
        ownerWxid: props.selectedWxid,
      });

      if (res.code === 20000) {
        Message.success('清空成功');
        await fetchTaskList(props.selectedWxid);
      } else {
        Message.error(res.msg || '清空失败');
      }
    } catch (error) {
      Message.error('清空失败');
    }
  };
  // 监听 selectedWxid 的变化
  watch(
    () => props.selectedWxid,
    async () => {
      if (props.selectedWxid) {
        await fetchTaskList(props.selectedWxid);
      }
    },
    { immediate: true }
  );

  const visibleCreateModal = ref(false);
  const visibleCreateGroupModal = ref(false);
  const handleOpenCreateModal = () => {
    visibleCreateModal.value = true;
  };
  const handleCreateModalCancel = () => {
    visibleCreateModal.value = false;
    fetchTaskList(props.selectedWxid);
  };
  const handleOpenCreateGroupModal = () => {
    visibleCreateGroupModal.value = true;
  };
  const handleCreateGroupModalCancel = () => {
    visibleCreateGroupModal.value = false;
    fetchTaskList(props.selectedWxid);
  };
</script>
